<template>
  <el-dialog :title="currentFile.fileName" v-model="fileOpen" append-to-body destroy-on-close class="preview-dialog" style="width: fit-content;">
    <vue-office-docx v-loading="loading" v-if="fileType === 'docx'" :src="src" style="height: 100vh;" @rendered="renderedHandler" @error="errorHandler" />
    <!-- <vue-office-excel v-loading="loading" v-if="fileType === 'xlsx'" :src="src" :options="xlsxOption" style="height: 80vh; width: auto; overflow-x: scroll;" @rendered="renderedHandler" @error="errorHandler" /> -->
    <!-- <el-table v-if="fileType === 'xlsx'" v-loading="loading" :data="xlsxData">
      <el-table-column v-for="(item, index) in xlsxData[0]" :key="item" :prop="index + ''" :label="item + ''"></el-table-column>
    </el-table> -->
    <el-table-v2 v-if="fileType === 'xlsx'" v-loading="loading" :columns="columns" :data="xlsxData" :width="700" :height="400" fixed />
    <vue-office-pdf v-loading="loading" v-if="fileType === 'pdf'" :src="src" style="height: 100vh" @rendered="renderedHandler" @error="errorHandler" />
    <el-image v-loading="loading" v-if="['jpg', 'png', 'jepg', 'gif'].includes(fileType)" class="w-125 h-auto" :src="src" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[src]" :initial-index="4" fit="cover" @load="renderedHandler" @error="errorHandler" />
    <p v-loading="loading" v-if="fileType === 'txt'" class="break-words" v-html="text"></p>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="fileOpen = false">关 闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="tsx">
import VueOfficeDocx from '@vue-office/docx';
// import VueOfficeExcel from '@vue-office/excel';
import VueOfficePdf from '@vue-office/pdf';
import { FilePreviewProps } from './types';
import * as XLSX from 'xlsx';
import { ElTooltip } from 'element-plus';
import { fontWidth } from '@/utils';

// const xlsxOption = ref<any>({
//   xls: false,       //预览xlsx文件设为false；预览xls文件设为true
//   minColLength: 0,  // excel最少渲染多少列，如果想实现xlsx文件内容有几列，就渲染几列，可以将此值设置为0.
//   minRowLength: 0,  // excel最少渲染多少行，如果想实现根据xlsx实际函数渲染，可以将此值设置为0.
//   widthOffset: 50,  //如果渲染出来的结果感觉单元格宽度不够，可以在默认渲染的列表宽度上再加 Npx宽
//   heightOffset: 10, //在默认渲染的列表高度上再加 Npx高
//   beforeTransformData: (workbookData: any) => {
//     return workbookData;
//   }, //底层通过exceljs获取excel文件内容，通过该钩子函数，可以对获取的excel文件内容进行修改，比如某个单元格的数据显示不正确，可以在此自行修改每个单元格的value值。
//   transformData: (workbookData: any) => {
//     return workbookData;
//   }, //将获取到的excel数据进行处理之后且渲染到页面之前，可通过transformData对即将渲染的数据及样式进行修改，此时每个单元格的text值就是即将渲染到页面上的内容
// });

const loading = ref<boolean>(true);
const renderedHandler = () => {
  console.log('渲染完成');
  loading.value = false;
};
const errorHandler = () => {
  console.log('渲染失败');
  loading.value = false;
};
const currentFile = ref<any>({});
const fileOpen = ref<boolean>(false);
const fileType = ref<string>('');
const src = ref<string>('');
const init = async (row: FilePreviewProps) => {
  currentFile.value = row;
  const fileArr = row.fileName.split('.');
  fileType.value = fileArr[fileArr?.length - 1].toLocaleLowerCase();
  src.value = row.previewUrl;
  fileOpen.value = true;
};

// 预览txt
const text = ref<string>('');
const getTxtContent = () => {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', src.value, true);
  xhr.responseType = 'blob';
  xhr.onload = function () {
    if (xhr.status === 200) {
      let reader = new FileReader();
      reader.readAsText(xhr.response, 'utf-8');//这里如果出现乱码可改成reader.readAsText(data, "")试试
      reader.onload = () => {
        getText(reader.result);
      };
    }
  };
  xhr.send();
};
const getText = (data: any) => {
  text.value = data.replace(/\n/g,'</br>');
  loading.value = false;
};

// 预览xlsx
const xlsx = ref<any>({});
const xlsxData = ref<any[]>([]);
const xlsxTitle = ref<any[]>([]);
const getTable = (sheetNames: any) => {
  const sheetName = sheetNames[0];
  const sheet = xlsx.value.Sheets[sheetName];
  const data = XLSX.utils.sheet_to_json(sheet, { header: 1 });
  xlsxTitle.value = data[0] as any[];
  columns.value = generateColumns(xlsxTitle.value.length);
  xlsxData.value = data.slice(1);
  loading.value = false;
};

const getXlsxContent = () => {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', src.value, true);
  xhr.responseType = 'arraybuffer';
  xhr.onload = function () {
    if (xhr.status === 200) {
      let res = new Uint8Array(xhr.response);
      const workbook = XLSX.read(res, { type: 'array' });
      const sheetNames = workbook.SheetNames;
      xlsx.value = workbook;
      getTable(sheetNames);
    }
  };
  xhr.send();
};
const generateColumns = (length = 10, prop?: any) =>{
  const width = 100;
  return Array.from({ length }).map((_, columnIndex) => {
    return {
      ...prop,
      title: xlsxTitle.value[columnIndex],
      width: width,
      align: 'center',
      key: columnIndex + '',
      dataKey: columnIndex + '',
      cellRenderer: ({ cellData }: any) => {
        return (
        fontWidth(cellData) > (width - 16) ?
        <ElTooltip content={cellData + ''}>
          {
            <span class={'whitespace-nowrap truncate'}>{cellData}</span>
          }
        </ElTooltip> : <span class={'whitespace-nowrap'}>{cellData}</span>
      );
      },
    };
  });
};

const columns = ref<any[]>([]);
watch(() => fileType.value, (val: string) => {
  if (val === 'txt') {
    getTxtContent();
  }
  else if (val === 'xlsx') {
    getXlsxContent();
  }
}, { immediate: true });

defineExpose({
  init
});
</script>

<style lang="scss">
.x-spreadsheet-selector {
  display: none !important;
}
</style>
